package com.cm.sys.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cm.sys.framework.application.ApiResponseCode;
import com.cm.sys.framework.execption.BusinessException;
import com.cm.sys.framework.utils.DateUtil;
import com.cm.sys.framework.utils.JsonUtil;
import com.cm.sys.framework.utils.PageList;
import com.cm.sys.system.dao.UserMapper;
import com.cm.sys.system.entity.User;
import com.cm.sys.system.entity.UserRole;
import com.cm.sys.system.service.UserRoleService;
import com.cm.sys.system.service.UserService;

/***
 * 用户模块
 * 
 * @author yxq18
 *
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private PageList pageList;

    @Override
    public User saveUser(JSONObject args) {
        logger.info("用户保存的入参==================【{}】===============", args);

        String userName = args.getString("userName");
        String password = args.getString("password");
        String userRole = args.getString("userRole");
        String remarks = args.getString("remake");

        User user = new User();
        user.setCreateTime(DateUtil.getTimestamp());
        user.setPassword(password);
        user.setRemarks(remarks);
        user.setUpdateTime(DateUtil.getTimestamp());
        user.setUserName(userName);
        user.setUserRole(0);
        logger.info("用户保存对象的入参==================【{}】===============", JSON.toJSONString(user));
        userMapper.insert(user);
        logger.info("用户保存返回的值==================【{}】===============", JSON.toJSONString(user));
        return user;
    }

    @Override
    public int delUser(JSONObject args, Integer userId) {

        logger.info("用户删除的入参==================【{}】===============", args);

        int count = 0;
        User user = selectUser(userId);
        if (!StringUtils.isEmpty(user)) {
            count = userMapper.deleteByPrimaryKey(user.getId());
        }
        return count;
    }

    @Override
    public User updateUser(JSONObject args, Integer userId) {
        logger.info("用户保存的入参==================【{}】===============", args);

        String userName = JsonUtil.getString(args, "userName", "");
        String password = JsonUtil.getString(args, "password", "");
        String userRole = JsonUtil.getString(args, "userRole", "");
        String remarks = JsonUtil.getString(args, "remake", "");

        User user = selectUser(userId);
        if (StringUtils.isEmpty(user)) {
            throw new BusinessException(ApiResponseCode.PARAM_NEED.getCode(), "所传userId查不到用户信息");
        }
        if (!StringUtils.isEmpty(userName)) {
            user.setUserName(userName);
        }
        if (!StringUtils.isEmpty(password)) {
            user.setPassword(password);
        }
        if (!StringUtils.isEmpty(userRole)) {
            userRoleService.deleteByUserId(userId);
            List<UserRole> list = getUserRole(userRole, userId);
            userRoleService.insertBatch(list);
        }
        if (!StringUtils.isEmpty(remarks)) {
            user.setRemarks(remarks);
        }

        user.setUpdateTime(DateUtil.getTimestamp());
        logger.info("用户对象更新的入参==================【{}】===============", JSON.toJSONString(user));
        userMapper.updateByPrimaryKey(user);
        return user;
    }

    @Override
    public Map<String, Object> selectUsers(JSONObject args) {

        logger.info("用户列表查询的入参==================【{}】===============", args);

        pageList.initPage(JsonUtil.getInt(args, "pageIndex", 1), JsonUtil.getInt(args, "pageSize", 10));

        String search = JsonUtil.getString(args, "search", "");
        List<Map<String, Object>> list = userMapper.selectAll(search);
        Map<String, Object> map = pageList.getData(list, Map.class);
        logger.info("用户列表查询的入参==================【{}】===============", map);
        return map;

    }

    @Override
    public User selectUser(Integer userId) {

        User user = new User();
        if (StringUtils.isEmpty(userId)) {
            throw new BusinessException(ApiResponseCode.PARAM_NEED.getCode(), "所传参数为空");
        } else {
            user = userMapper.selectByPrimaryKey(userId);
        }

        return user;
    }

    @Override
    public User verifyUser(Integer userId, String password) {

        User user = userMapper.verifyUser(userId, password);

        return user;
    }

    @Override
    public User accountUser(String userName, String password) {
        User user = userMapper.accountUser(userName, password);
        return user;
    }

    @Override
    public User updateUser(User user) {
        logger.info("用户更新的入参==================【{}】===============", user);

        user.setUpdateTime(DateUtil.getTimestamp());
        logger.info("用户对象更新的入参==================【{}】===============", JSON.toJSONString(user));
        userMapper.updateByPrimaryKey(user);
        return user;
    }

    @Override
    public void updateToken(Integer userId, String token) {

        logger.info("用户更新token的入参====用户id【{}】=========token【{}】======", userId, token);

        userMapper.updateToken(userId, token);

    }

    @Override
    public List<UserRole> getUserRole(String userRole, Integer userId) {
        String[] roles = userRole.split(",");
        List<UserRole> list = new ArrayList<UserRole>();
        for (String roleId : roles) {
            UserRole ur = new UserRole();
            ur.setRoleId(Integer.valueOf(roleId));
            ur.setCreateTime(DateUtil.getTimestamp());
            ur.setUserId(userId);
            ur.setUpdateTime(0);
            list.add(ur);
        }
        return list;

    }

}
